package com.work.cloudseata.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.work.cloudseata.common.Ret;
import com.work.cloudseata.entity.User;
import com.work.cloudseata.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService service;

    @SaIgnore
    @PostMapping("/user/register")
    public Ret<Void> register(@Validated @RequestBody User user, HttpServletRequest request) {
        service.register(user, request.getRemoteAddr());
        return Ret.ok();
    }

    @SaIgnore
    @PostMapping("/user/login")
    public Ret<String> login(@Validated @RequestBody User user) {
        return Ret.ok(service.login(user.getUsername(), user.getPassword()));
    }

    @GetMapping("/users")
    public Ret<List<User>> users() {
        return Ret.ok(service.list());
    }

    @GetMapping("/user/{id}")
    public Ret<User> getById(@PathVariable Long id) {
        return Ret.ok(service.getById(id));
    }

    @PutMapping("/user/{id}")
    public Ret<Void> update(@PathVariable Long id, @Validated @RequestBody User user) {
        service.updateById(id, user);
        return Ret.ok();
    }

    @PostMapping("/user/reset-password")
    public Ret<Void> resetPassword(@Validated @RequestBody User user) {
        service.resetPassword(user);
        return Ret.ok();
    }

    @PostMapping("/user/{id}/upgrade")
    public Ret<Void> upgrade(@PathVariable Long id) {
        service.upgrade(id);
        return Ret.ok();
    }

    @PostMapping("/user/{id}/downgrade")
    public Ret<Void> downgrade(@PathVariable Long id) {
        service.downgrade(id);
        return Ret.ok();
    }
}
